package com.simpleactors;

/**
 * @author Dmitry
 */
public class MostFreeActorsWrapper extends MultipleActorsWrapper {
    public MostFreeActorsWrapper(String name, Actor... actors) {
        super(name, actors);
    }

    @Override
    public boolean send(Object value, Actor sender) {
        if (size == 0) {
            throw new IllegalStateException("RoundRobinActor does not contain any actors inside");
        }
        lock.lock();
        try {
            int minSize = actors[0].getQueueSize();
            int minIndex = 0;
            for (int i = 1; i < size; i++) {
                Actor actor = actors[i];
                int size = actor.getQueueSize();
                if (size == 0) {
                    return actor.send(value, sender);
                }
                if (size < minSize) {
                    minSize = size;
                    minIndex = i;
                }
            }

            return actors[minIndex].send(value, sender);
        } finally {
            lock.unlock();
        }
    }
}
